import hashlib
import os
from flask import render_template, request, session, g, jsonify, current_app


from app import db
from app.models.models import Cartoon, Chapter, User, Video, Comment, Classify
from app.models.models import Cartoon, Chapter, User, News, Comment, Video, RechargeCard

# from app.utils.images.qiniu import
from app.views.index import index_blu
from app.utils.common.common import login_user_data, login_user_data_redirect
from datetime import datetime,timedelta


@index_blu.route('/index')
@index_blu.route('/')
@login_user_data
def index():
    # 查询数据库
    # if not g.user:
    #     return render_template("index/index.html")
    pages = db.session.query(Cartoon).all()
    class_0 = db.session.query(Classify).all()
    return render_template('index/index.html', pages=pages, user=g.user, class_0=class_0)


@index_blu.route('/detail/<int:page_id>')
@login_user_data
def detail(page_id):
    if request.method == "GET":
        pages = db.session.query(Cartoon).filter(Cartoon.id == page_id).first()
        chapters = db.session.query(Chapter).filter(Chapter.cartoon_id == pages.id).all()
        chapter_num = len(chapters)
        # 得到当前新闻评论的所有信息
        comments = [x.to_basic_dict() for x in pages.comments.order_by(Comment.create_time.desc())]
        print(comments)
        # user_id = session.get('user_id')
        # print(user_id)
        session['page_id'] = page_id
        return render_template('index/detail.html', pages=pages, chapter_num=chapter_num, chapters=chapters, user=g.user, comments=comments)


@index_blu.route('/detail2', methods=["GET", "POST"])
@login_user_data
def detail2():
    if request.method == "POST":
        print("------------------------------------------------------------------------")
        print(request.json)
        content = request.json.get("content")
        ret = {"errno":0, "comment":content}
        return jsonify(ret)


@index_blu.route("/Comic_consulting")
@login_user_data
def Comic_consulting():
    # 1. 查询点击排行的前6个数据
    print("123456")
    rank_news = db.session.query(News).order_by(News.clicks.desc()).limit(6)  # 从news数据表中查询点击最高的6个数据
    print(rank_news)
    # 如果用户登录成功，那么它就有session值，取出这些值来
    user = g.user

    return render_template("index/Comic_consulting.html", rank_news=rank_news, user=user)
@index_blu.route("/newslist")
def newslist():

    # 0. 提取数据
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)

    page = int(page) if page.isalnum() else 1

    per_page = int(per_page) if per_page.isalnum() else 10

    # 1. 先从数据库中查询

    paginate = db.session.query(News).filter().paginate(page, per_page, False)
    news_list = paginate.items  # 查询出来的对象组成的列表

    # 2. 将查询出来的数据模型对象转化为需要的字典格式
    ret = {
        "totalPage": paginate.pages,
        "newsList": [news.to_dict() for news in news_list]
    }

    # 3. 将字典格式的数据转换为json格式，返回给前端
    # return jsonify(news_list)  # 这种方式不能使用，因为news中是News类的实例对象，使用jsonify不能将其转换为json格式，
    # 所以我们需要，先将news对象转化为普通的字典类型，然后再转化为json
    return jsonify(ret)


@index_blu.route("/detail3/<int:news_id>")
@login_user_data
def detail3(news_id):
    # 如果用户登录成功，那么它就有session值，取出这些值来

    # 根据id来查询新闻
    news = db.session.query(News).filter(News.id == news_id).first()
    if g.user and (g.user.id in [x.id for x in news.collection_user]):
        print("收藏过.....")
        g.user.can_collect = False
    else:
        g.user.can_collect = True
    # 查询点击靠前的前6个新闻
    rank_news = db.session.query(News).order_by(News.clicks.desc()).limit(6)  # 从news数据表中查询点击最高的6个数据

    return render_template("index/detail3.html",
                           news=news,
                           rank_news=rank_news,
                           user=g.user,
                           )


@index_blu.route('/light_novel')
@login_user_data_redirect
def light_novel():
    time_sign = None
    if g.user.vip_time:
        time = g.user.vip_time - datetime.now()
        if time < timedelta(0):
            time_sign = None
        elif time > timedelta(0):
            time_sign = True
    content = db.session.query(Video).all()

    return render_template('index/light_novel.html', videos = content, time_sign=time_sign, user=g.user)


@index_blu.route('/personal_center')
@login_user_data_redirect
def personal_center():
    return render_template('index/personal_center.html', user=g.user)


@index_blu.route('/user_base_info', methods=['GET', 'POST'])
def user_base_info():
    # 获取当前用户的信息
    user_id = session.get("user_id")
    # 存储到数据库
    user = db.session.query(User).filter(User.id == user_id).first()
    if request.method == "GET":
        return render_template("index/user_base_info.html", user=user)
    elif request.method == "POST":
        # 获取用户的新的信息
        nick_name = request.json.get("nick_name")
        signature = request.json.get("signature")
        gender = request.json.get("gender")
        print(nick_name, signature, gender)
        # 判断用户输入的数据是否完整
        if not all([nick_name, gender]):
            ret = {
                "errno": 4001,
                "errmsg": "缺少参数"
            }

            return jsonify(ret)

        if not user:
            ret = {
                "errno": 4002,
                "errmsg": "没有此用户"
            }

            return jsonify(ret)

        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender

        db.session.commit()

        ret = {
            "errno": 0,
            "errmsg": "修改成功"
        }
        return jsonify(ret)


@index_blu.route('/user_pic_info', methods=["GET", "POST"])
@login_user_data_redirect
def user_pic_info():
    if request.method == "GET":
        return render_template("index/user_pic_info.html", user=g.user)
    elif request.method == "POST":
        f = request.files.get("avatar")
        if f:
            # 存储到哪个路径呢？文件名叫什么呢？
            file_hash = hashlib.md5()
            file_hash.update(f.filename.encode("utf-8"))
            file_name = file_hash.hexdigest() + f.filename[f.filename.rfind("."):]
            local_file_path = os.path.join("/static/upload/images", file_name)
            # file_path = /Users/wangmingdong/Desktop/个人简历7/app/static/upload/images/'dfa72f3bf97b709023b6136d4e5a0566.png
            file_path = os.path.join(current_app.root_path, "static/upload/images", file_name)  # f.filename是你刚刚在浏览器选择的那个上传的图片的名字
            f.save(file_path)  # a/b/c/123.png

            # upload_image(file_path, file_name)

            # 3. 将数据库中对应head_image字段值改为 刚刚保存的图片的路径
            g.user.avatar_url = local_file_path
            db.session.commit()

            ret = {
                "errno": 0,
                "errmsg": "上传头像成功",
                "avatar_url": local_file_path
            }

            return jsonify(ret)
        else:
            ret = {
                "errno": 4005,
                "errmsg": "上传头像失败"
            }

            return jsonify(ret)


@index_blu.route('/vip_png')
def vip_png():
    return render_template('index/vip_png.html')


@index_blu.route('/user_pass_info', methods=["GET", "POST"])
@login_user_data_redirect
def user_pass_info():
        if request.method == "GET":
            return render_template("index/user_pass_info.html")
        elif request.method == "POST":
            # 1. 提取旧密码以及新密码
            new_password = request.json.get("new_password")
            old_password = request.json.get("old_password")

            # 如果提交时，只有一部分数据，则返回提示
            if not all([new_password, old_password]):
                ret = {
                    "errno": 4003,
                    "errmsg": "缺少参数"
                }
                return jsonify(ret)

            user = g.user
            if user.password_hash == old_password:
                user.password_hash = new_password
                db.session.commit()
                ret = {
                    "errno": 0,
                    "errmsg": "修改成功"
                }

            else:
                ret = {
                    "errno": 4004,
                    "errmsg": "原密码错误！"
                }

            # 4. 返回json
            return jsonify(ret)


@index_blu.route("/user_collection")
@login_user_data
def user_collection():
    page = request.args.get("page", 1)
    paginate = g.user.collection_news.paginate(int(page), 1, False)
    collection_news = [x.to_collect_dict() for x in paginate.items]
    print(collection_news)
    return render_template("index/user_collection.html", collection_news=collection_news, paginate=paginate)


# @index_blu.route('/pay')
# @login_user_data_redirect
# def pay():
#     return render_template('index/pay.html', user=g.user)

@index_blu.route('/pay', methods=["POST", "GET"])
@login_user_data_redirect
def pay():
    if request.method == "GET":
        return render_template('index/pay.html', user=g.user)
    elif request.method == "POST":
        print(request.json)
        code = request.json.get("code")
        if not code:
            ret = {"errno": 2, "errmsg": "充值卡编码不能为空"}
            return jsonify(ret)
        recharge = db.session.query(RechargeCard).filter(RechargeCard.code_num == code).first()
        if not recharge:
            # print(recharge)
            ret = {"errno": 3, "errmsg": "错误充值码"}
            return jsonify(ret)
        if recharge.user_id:
            ret = {"errno": 3, "errmsg": "此卡已使用"}
            return jsonify(ret)
        print(recharge.user_time, "有效期", type(recharge.user_time))
        print("asdfasfd")
        print(datetime.now().strftime("%Y-%m-%d"), "fasdasfd")
        print("afsdfasdf", datetime.now())
        c = datetime.now() - recharge.user_time
        c = str(c)
        print(type(c), str(c))

        if "-" in c:
            print("未过期")
            ret = {"errno": 1, "errmsg": "充值成功"}
            user = g.user
            recharge.user_id = user.id
            # print("充值开始")
            # db.session.commit()
            # print("充值结束")
            user.vip += 1
            # print("操作完成")
            if user.vip == 1:
                user.vip_time = datetime.now() + timedelta(30)
                print("11111111111111", datetime.now() + timedelta(30))
                db.session.commit()
            else:
                # user = g.user
                print("----------------------------")
                # user.vip_time += timedelta(30)
                vip_lost_time = user.vip_time - datetime.now()
                # print(vip_lost_time.days, type(vip_lost_time.days))
                time_vip = 30 + vip_lost_time.days
                print(time_vip, type(time_vip), "---------------------------")
                time__ = datetime.now() + timedelta(days=time_vip)
                print(time__)
                print(type(datetime.now()))
                print(type(timedelta(time_vip)))
                # 测试
                print(user.vip_time)
                user.vip_time = datetime.now() + timedelta(days=time_vip)

                print("222222222222222222222222222222222", type(user.vip_time), user.vip_time)
                print(user.vip_time, "user")
                print(user.id, "user")
                print(user.vip, "user")
                db.session.commit()

                print("----------------------------")


            return jsonify(ret)
        else:
            print("过期")
            ret = {"errno": 4, "errmsg": "充值码已过期"}
            return jsonify(ret)
        # 一下为充值成功

@index_blu.route('/detail_index')
def detail_index():
    page_id = session.get('page_id')
    pages = db.session.query(Cartoon).filter(Cartoon.id == page_id).first()
    chapters = db.session.query(Chapter).filter(Chapter.cartoon_id == pages.id).all()
    for x in chapters:
        print(x.url)
    return render_template('index/detail_index.html', chapters=chapters, pages=pages)

